// 获取DOM元素
const audioInput = document.getElementById("audioInput");
const confirmBtn = document.getElementById("confirmBtn");
const audioUploadButton = document.getElementById("audioUploadButton");
const uploadAudioImg = document.querySelector(".upload-audio-img");
const uploadedAudioContainer = document.getElementById(
  "uploadedAudioContainer"
);
const uploadedAudio = document.getElementById("uploadedAudio");
const audioInfo = document.getElementById("audioInfo");
const backBtn = document.querySelector(".back-btn"); // 返回按钮

// 返回按钮功能：点击返回上一页
function setupBackButton() {
  backBtn.addEventListener("click", () => {
    window.history.back();
  });
}

// 音频上传按钮点击事件
function setupAudioUploadButton() {
  uploadAudioImg.addEventListener("click", (e) => {
    e.stopPropagation();
    audioInput.click();
  });
}

// 监听音频文件选择变化
function setupAudioInputChange() {
  audioInput.addEventListener("change", (e) => {
    const file = e.target.files[0];
    if (!file) return;

    if (!file.type.startsWith("audio/")) {
      alert("请选择音频文件（MP3/WAV等）");
      return;
    }

    const reader = new FileReader();
    reader.onload = (event) => {
      audioUploadButton.style.display = "none";
      uploadedAudioContainer.style.display = "block";
      uploadedAudio.src = event.target.result;
      audioInfo.textContent = `已上传：${file.name}`;
    };
    reader.onerror = () => {
      alert("读取音频文件时出错，请重试。");
    };
    reader.readAsDataURL(file);

    confirmBtn.disabled = false;
  });
}

// 确定按钮事件
function setupConfirmButton() {
  confirmBtn.addEventListener("click", () => {
    const file = audioInput.files[0];
    if (!file) {
      alert("请先上传音频文件");
      return;
    }

    const formData = new FormData();
    formData.append("audio", file);

    alert(`音频 "${file.name}" 已准备上传，即将调用后端接口`);

    // 真实接口调用示例：
    
    fetch("http://127.0.0.1:5000/api/upload-audio", {
      method: "POST",
      body: formData
    })
      .then(response => response.json())
      .then(data => {
        if (data.success) {
          alert("音频上传成功！");
        } else {
          alert("铛铛：" + data.message);
        }
      })
      .catch(err => {
        console.error("上传出错：", err);
        alert("网络错误，请重试");
      });
    
  });
}

// 初始化函数
function init() {
  setupBackButton();
  setupAudioUploadButton();
  setupAudioInputChange();
  setupConfirmButton();
}

// 页面加载完成后执行初始化函数
window.addEventListener("load", init);
